angular.module("application")
.controller('chooseCtrl', function($scope, $interval, chooseProcess) {
	$scope.viewSection = 1;

	$scope.qData = [];
	$scope.qGroups = [];
	$scope.questionList = [];
	$scope.randomList = [];
	$scope.numQuestion = '8';
	$scope.answerList = [];
	$scope.countAnswer = 0;
	$scope.score = '';


	// $scope.time = {minute: 15, second: 0};
	$scope.status = "stop";

	chooseProcess.getData().then(function(data) {
		setTimeout(function() {
			$scope.$apply(function() {
				$scope.$parent.loadingView = false;
			})
		},500);

		$scope.qData = data.ungroup;
		$scope.qGroups = data.group;

		for(i = 0; i < $scope.qData.length; i++) {
			if($scope.qData[i].questions.length > 0)
				$scope.randomList.push(false);
		}
		console.log($scope.qGroups);
	});

	$scope.getExam = function(group) {
		$scope.questionList = group;
		$scope.answerList = [];
		for(i = 0; i < group.length; i++) {
			$scope.answerList.push(null);
		}
		$scope.status = 'stop';
		$scope.viewSection = 3;
	}
	$scope.getRandomExam = function() {
		arrQ = []; arrCat = [];
		for(i in $scope.qData) {
			if($scope.qData[i].questions.length > 0)
				arrCat.push($scope.qData[i]);
		}
		angular.forEach(arrCat, function(cat,i) {
			if($scope.randomList[i] == true) {
				for(m in cat.questions) {
					arrQ.push(cat.questions[m]);
				}
			}
		});

		if(arrQ.length < $scope.numQuestion) {
			getAlert('Số lượng câu hỏi trong các chủ đề không đủ để thực hiện gói ' + $scope.numQuestion + ' câu hỏi <br>' +
				'Vui lòng chọn gói khác hoặc chọn thêm chủ đề');
			return;
		}

		$scope.questionList = [];
		for(i = 0; i < $scope.numQuestion; i++) {
			index = Math.floor(Math.random()*arrQ.length);
			q = {};
			angular.copy(arrQ[index], q);
			$scope.questionList.push(q);
			arrQ.splice(index,1);
		}
		
		$scope.answerList = [];
		for(i = 0; i < $scope.questionList.length; i++) {
			$scope.answerList.push(null);
		}
		$scope.status = 'stop';
		$scope.viewSection = 3;
	}	
	$scope.toggleCat = function(index) {
		cat = $scope.randomList[index];
		if(cat) $scope.randomList[index] = false;
		else $scope.randomList[index] = true;
	}

	$scope.choose = function(index, opt) {
		if($scope.status == 'start') {
			$scope.answerList[index] = opt;
		}
	}
	$scope.startTest = function() {
		if($scope.status != 'play' && $scope.questionList.length > 0) {
			countDown = $interval(function() {
				if($scope.time.second == 0) {
					$scope.time.second = 60;
					$scope.time.minute--;
				}
				$scope.time.second--;

				if($scope.time.minute == 0 && $scope.time.second == 0) {
					$interval.cancel(countDown);
					getAlert('Hoàn thành');
					$scope.status = 'complete';
					$scope.viewSection = 3;
					$scope.score = '0/' + $scope.questionList.length;

					$("#confirmExam").modal('hide');
				}
			}, 1000);

			$scope.answerList = [];
			for(i = 0; i < $scope.questionList.length; i++) {
				$scope.answerList.push(null);
			}
			$scope.status = 'start';
		}
		else if($scope.questionList.length <= 0) {
			getAlert('Vui lòng chọn gói câu hỏi để làm.')
		}
	}
	$scope.scoreAct = function() {
		if($scope.status == 'start') {
			$interval.cancel(countDown);
			count = 0;
			for(i = 0; i < $scope.questionList.length; i++) {
				if($scope.questionList[i].result == $scope.answerList[i]) {
					count++;
				}
			}
			$scope.score = count + '/' + $scope.questionList.length;
		}
		$scope.status = 'complete';
	}

	$scope.$watch('viewSection', function(val) {
		if($scope.questionList.length <= 8) {
			$scope.time = {minute: 5, second: 0};
		}
		else switch($scope.questionList.length) {
			case 10: $scope.time = {minute: 10, second: 0};
			break;
			case 20: $scope.time = {minute: 20, second: 0};
			break;
			case 45: $scope.time = {minute: 30, second: 0};
			break;
			default: $scope.time = {minute: 30, second: 0};
		}
	})

	// =======================================================================================
	// =======================================================================================
	$(window).scroll(function() {
		if($(window).scrollTop() >= 190) {
			$('.choosetest.sections .heading').css({
				"position": "fixed", 'width': "100%",
				"top": "35px", "left": "0"
			})
		}
		else $('.choosetest.sections .heading').css('position', 'static');
	})

})
.factory('chooseProcess', function($http, BASE_URL) {
	return {
		getData: function() {
			return $http.post(BASE_URL + 'application_api/question/getOptQuestions')
			.then(function(promise) {
				arr = [];
				angular.copy(promise.data, arr);
				qGroups = [];
				angular.forEach(arr, function(section) {
					var sec = {}
					sec.name = section.name;
					sec._id = section._id;
					sec.groups = [];

					mod = section.questions.length % 8;
					set = section.questions.length - mod
					for(i = 0; i < set/8; i++ ) {
						gr = section.questions.splice(0, 8);
						sec.groups.push(gr);
					}
					if(mod != 0)
						sec.groups.push(section.questions);
					if(sec.groups.length > 0)
						qGroups.push(sec);
				});

				console.log(promise.data);
				return {
					ungroup: promise.data,
					group: qGroups
				}
			})
		}
	}
})

// =======================================================================================
// =======================================================================================
// =======================================================================================
// =======================================================================================
.controller('questionCtrl', function($scope, advanceProcess) {
	$scope.viewSection = 1;
	$scope.categories = [];

	$scope.vnFilter = {cat:''};
	$scope.woFilter = {cat:''};

	advanceProcess.getQuestions().then(function(data) {
		$scope.questionList = data;
		setTimeout(function() {
			$scope.$apply(function() {
				$scope.$parent.loadingView = false;
			})
		},500);
	})		

	advanceProcess.getCategories().then(function(data) {
		parentArr = []; childArr = [];
		angular.forEach(data, function(cat) {
			if(!cat.parent) parentArr.push(cat);
			else childArr.push(cat);
		});		
		angular.forEach(parentArr, function(par) {
			par.child = [];
			angular.forEach(childArr, function(child) {
				if(child.parent == par._id) {
					par['child'].push(child);
				}
			});
			$scope.categories.push(par);
		});
	})
})
.controller('questionDtCtrl', function($scope, $sce, $routeParams, advanceProcess) {
	$scope.type="question";
	$scope.qsId = $routeParams.qsId;

	advanceProcess.getQuestion($scope.qsId).then(function(data) {
		$scope.question = data.question;
		$scope.content = $sce.trustAsHtml(data.answer);
	})

	setTimeout(function() {
		$scope.$apply(function() {
			$scope.$parent.loadingView = false;
		})
	},500);
})
.factory('advanceProcess', function($http, BASE_URL) {
	return {
		getQuestions: function() {
			return $http.post(BASE_URL + 'application_api/question/getAdvanceQuestions')
			.then(function(promise) {
				return promise.data;
			})
		},
		getCategories: function() {
			return $http.post(BASE_URL + 'application_api/category/getAllCats')
			.then(function(promise) {
				return promise.data;
			})
		},
		getQuestion: function(id) {
			return $http.post(BASE_URL + 'application_api/question/getAdvanceQuestion/' + id)
			.then(function(promise) {
				console.log(promise.data);
				return promise.data;
			})
		}
	}
})